#include "stringmodel.h"
#include <QDebug>

StringModel::StringModel(QObject *parent)
    : QAbstractListModel(parent)
{
    addItem(0, "Kitty", "Beijin", "89");
    addItem(0, "Tom", "Beijin", "75");
    addItem(0, "Jack", "Beijin", "100");
}

Qt::ItemFlags StringModel::flags(const QModelIndex &index) const
{
    if (!index.isValid())
        return Qt::ItemIsEnabled;
    return QAbstractListModel::flags(index) | Qt::ItemIsEditable;
}

QVariant StringModel::data(const QModelIndex &index, int role) const
{
    if (!index.isValid()){
        return QVariant();
    }

    if (index.row() >= m_string_lists[0].size()){
        return QVariant();
    }

    switch (role) {
    case NAME_ROLE:
        return m_string_lists[NAME_ROLE].at(index.row());
        break;
    case CITY_ROLE:
        return m_string_lists[CITY_ROLE].at(index.row());
        break;
    case SCORE_ROLE:
        return m_string_lists[SCORE_ROLE].at(index.row());
    default:
        return QVariant();
        break;
    }

    return QVariant();
}

bool StringModel::setData(const QModelIndex &index, const QVariant &value, int role)
{
    if (!index.isValid() || role >= ROLE_MAX){
        return false;
    }
    m_string_lists[role].replace(index.row(), value.toString());
    emit dataChanged(index, index);
    return true;
}

int StringModel::rowCount(const QModelIndex &parent) const
{
    Q_UNUSED(parent);
    return m_string_lists[0].count();
}

QHash<int, QByteArray> StringModel::roleNames() const
{
    QHash<int, QByteArray> names;
    names.insert(NAME_ROLE, "name");
    names.insert(CITY_ROLE, "city");
    names.insert(SCORE_ROLE, "score");
    return names;
}

void StringModel::addItem(int row, const QString &name, const QString &city, const QString &score)
{
    beginInsertRows(QModelIndex(), row, row);
    m_string_lists[NAME_ROLE].insert(row, name);
    m_string_lists[CITY_ROLE].insert(row, city);
    m_string_lists[SCORE_ROLE].insert(row, score);
    endInsertRows();
}
